from api.Agefans_app import AgeAppApi
from urllib.parse import unquote, urlparse
from api.m88ysApi import getPlayUrl as get88ysPlayUrl


def ck_player_url_handler(link):
    url = urlparse(url=link)
    for query in url.query.split("&"):
        v = query.split("=")
        if v[0] == 'url':
            if len(v) == 2:
                real_link = unquote(v[1]).strip()
                if real_link.endswith('.m3u8'):
                    return real_link, 0
                else:
                    return real_link, 1
            else:
                break
    raise Exception("解析CKPlayer播放链接失败:" + link)


def handler_real_download_url(api: AgeAppApi, play_id: str, vid: str):
    """
    获取下载链接
    :param api: Age App API
    :param play_id: 播放ID
    :param vid: 必要参数
    :return 真实下载链接, 下载模式[0: m3u8, 1: http]
    """
    playUrlInfo = api.get_play_url(play_id=play_id, vid=vid)
    visit_url = playUrlInfo['purlf'] + playUrlInfo['vurl']
    if visit_url.find("player/dp2") > -1 or visit_url.find('player/dpx') > -1:
        return ck_player_url_handler(visit_url)
    raise Exception(f"未知播放类型,play_id={play_id}, vid={vid}")


def handler_88kan_play_url(playUrl: str):
    """
    处理88kan播放链接
    :param playUrl: 播放链接
    :return 真实下载链接, 下载模式[0: m3u8, 1: http]
    """
    if playUrl.find("") > -1:
        return get88ysPlayUrl(url=playUrl), 0
    else:
        if playUrl.find(".m3u8") > -1:
            return playUrl, 0
        else:
            return playUrl, 1
